import 'package:fish_redux/fish_redux.dart' hide PageProvider;
import 'package:flutter/material.dart';
import 'package:wowhy/pages/search_page/page.dart';

import 'global/state.dart';
import 'global/store.dart';

import 'modules/page_provider.dart';
import 'pages/demo_page/demo_page.dart';
import 'pages/demo_page/picker_view.dart';
import 'pages/demo_page/scan_view.dart';

import 'pages/index_page/page.dart';
import 'pages/login_page/page.dart';
// import 'widgets/popup_window.dart';

dynamic _combineState(Object pagestate, GlobalState appState) {
  if (pagestate is GlobalBaseState) {
    final GlobalBaseState p = pagestate;
    if (p.themeColor == appState.themeColor) {
      return pagestate;
    } else {
      if (pagestate is Cloneable) {
        final Object copy = pagestate.clone();
        final GlobalBaseState newState = copy;
        newState.themeColor = appState.themeColor;
        return newState;
      }
    }
  } else {
    return pagestate;
  }
}

dynamic _combinePages(Map<String, Page<Object, dynamic>> pages1,
    Map<String, Page<Object, dynamic>> pages2) {
  Map<String, Page<Object, dynamic>> pages = {};
  pages.addAll(pages1);
  pages.addAll(pages2);
  print(pages);
  return pages;
}

final AbstractRoutes routes = PageRoutes(
  pages: _combinePages(
    <String, Page<Object, dynamic>>{
      'index': IndexPage(),
      'login': LoginPage(),
      'search': SearchPage(),
    },
    PageProvider.getRoutes(),
  ),
  visitor: (String path, Page<Object, dynamic> page) {
    if (page.isTypeof<GlobalBaseState>()) {
      page.connectExtraStore<GlobalState>(GlobalStore.store, _combineState);
    }

    page.enhancer.append(
      viewMiddleware: <ViewMiddleware<dynamic>>[safetyView<dynamic>()],
      adapterMiddleware: <AdapterMiddleware<dynamic>>[safetyAdapter<dynamic>()],
      effectMiddleware: [],
      middleware: <Middleware<dynamic>>[logMiddleware<dynamic>()],
    );
  },
);

Route<dynamic> buildRoute(RouteSettings settings) {
  if (settings.name == 'demo') {
    return MaterialPageRoute(builder: (context) => DemoPage());
  }

  switch (settings.name) {
    case 'demo':
      return MaterialPageRoute(builder: (context) => DemoPage());

    case 'picker_demo':
      return MaterialPageRoute(builder: (context) => PickerViewDemo());

    case 'scan_demo':
      return MaterialPageRoute(builder: (context) => ScanViewDemo());

    // case 'search':
    //   return PopupLayout(
    //       child: routes.buildPage(settings.name, settings.arguments));

    default:
      return MaterialPageRoute<Object>(builder: (BuildContext context) {
        return routes.buildPage(settings.name, settings.arguments);
      });
  }
}
